package com.qys.livesMall.app.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.app.user.mapper.H2AppUserAddressMapper;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.dto.AppBaseDTO;
import com.qys.livesMall.app.user.model.dto.app.AppUserAddressDTO;
import com.qys.livesMall.app.user.model.dto.sys.SysUserAddressDTO;
import com.qys.livesMall.app.user.model.dto.sys.SysUserAddressPageDTO;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.entity.H2AppUserAddress;
import com.qys.livesMall.app.user.model.vo.sys.H2AppUserAddressVO;
import com.qys.livesMall.app.user.service.IH2AppUserAddressService;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.framework.view.BaseQuery;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户收货地址 服务实现类
 * </p>
 *
 * @author dp
 * @since 2023-04-24
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class H2AppUserAddressServiceImpl extends ServiceImpl<H2AppUserAddressMapper, H2AppUserAddress> implements IH2AppUserAddressService {

    private final H2AppUserMapper appUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String save(AppUserAddressDTO appUserAddressDTO, String userId) {
        log.info("保存用户地址信息: {},用户id: {}", appUserAddressDTO, userId);
        if (StringUtils.isBlank(appUserAddressDTO.getReceiveUserName())){
            throw new QysException(MessageUtils.message("app.receiveUserName.error"));
        }
        if (StringUtils.isBlank(appUserAddressDTO.getMobile())){
            throw new QysException(MessageUtils.message("app.mobile.error"));
        }
        if (StringUtils.isBlank(appUserAddressDTO.getAddress())){
            throw new QysException(MessageUtils.message("app.address.error"));
        }
        H2AppUser h2AppUser = appUserMapper.selectById(userId);
        if (null == h2AppUser) {
            throw new QysException(MessageUtils.message("app.getuser.error"));
        }

        //默认地址需要将之前的地址设为非默认地址
        if (null !=appUserAddressDTO.getDefaultAddress() && appUserAddressDTO.getDefaultAddress()) {
            resetDefaultAddress(userId);
        }

        //保存地址信息
        H2AppUserAddress address = new H2AppUserAddress();

        BeanUtils.copyProperties(appUserAddressDTO, address);
        address.setUserName(appUserAddressDTO.getReceiveUserName());
        address.setUserId(userId);
        address.setUpdateTime(LocalDateTime.now());
        if (StringUtils.isNotBlank(appUserAddressDTO.getId())) {
            address.setCreateTime(LocalDateTime.now());
        }

        saveOrUpdate(address);
        return address.getId();
    }

    /**
     * 根据用户id将用户默认地址清空
     *
     * @param userId
     */
    private void resetDefaultAddress(String userId) {
        LambdaQueryWrapper<H2AppUserAddress> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(H2AppUserAddress::getUserId,userId);
        H2AppUserAddress address = new H2AppUserAddress();
        address.setDefaultAddress(false);
        baseMapper.update(address,wrapper);
    }

    @Override
    public Page<H2AppUserAddress> page(BaseQuery baseQuery, Long userId) {
        LambdaQueryWrapper<H2AppUserAddress> wrapper = Wrappers.lambdaQuery();
        if (null != userId) {
            wrapper.eq(H2AppUserAddress::getUserId, userId);
        }
        if (StringUtils.isNotBlank(baseQuery.getId())) {
            wrapper.eq(H2AppUserAddress::getId, baseQuery.getId());
        }

        return baseMapper.selectPage(new Page<>(baseQuery.getPageNum(), baseQuery.getPageSize()), wrapper);
    }

    @Override
    public Page<H2AppUserAddressVO> page(SysUserAddressPageDTO queryDTO) {
        return baseMapper.selectPageByUserType(new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()), queryDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultAddress(String id) {
        //默认地址需要将之前的地址设为非默认地址
        resetDefaultAddress(String.valueOf(SecurityUtils.getUserId()));

        //将新的地址设置为默认地址
        H2AppUserAddress address = new H2AppUserAddress();
        address.setId(id);
        address.setDefaultAddress(true);
        address.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(address);
    }

    @Override
    public H2AppUserAddress getByUserId(Long userId) {
        LambdaQueryWrapper<H2AppUserAddress> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(H2AppUserAddress::getUserId, userId);
        wrapper.eq(H2AppUserAddress::getDefaultAddress,true);
        wrapper.last("limit 1");
        return getOne(wrapper);
    }

    @Override
    public H2AppUserAddress getByUserIds(List<Long> userId) {
        LambdaQueryWrapper<H2AppUserAddress> wrapper = Wrappers.lambdaQuery();
        wrapper.in(H2AppUserAddress::getUserId, userId);
        wrapper.eq(H2AppUserAddress::getDefaultAddress,true);
        wrapper.last("ORDER BY RAND() limit 1");
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultAddressByUserId(SysUserAddressDTO dto) {
        //默认地址需要将之前的地址设为非默认地址
        resetDefaultAddress(dto.getUserId());

        //将新的地址设置为默认地址
        H2AppUserAddress address = new H2AppUserAddress();
        address.setId(dto.getId());
        address.setDefaultAddress(true);
        address.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(address);
    }

    @Override
    public List<Long> getExistByUserIds(List<Long> userIds) {
        LambdaQueryWrapper<H2AppUserAddress> wrapper = Wrappers.lambdaQuery();
        wrapper.in(H2AppUserAddress::getUserId, userIds.stream().map(String::valueOf).collect(Collectors.toList()));
        wrapper.eq(H2AppUserAddress::getDefaultAddress,true);
        List<H2AppUserAddress> list=list(wrapper);
        if (CollectionUtils.isNotEmpty(list)){
            return list.stream().map(H2AppUserAddress::getUserId).map(Long::valueOf).collect(Collectors.toList());
        }
        return null;
    }
}
